import { createRouter, createWebHistory } from 'vue-router'
import auth from '@/utils/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/home' },
    {
      path: '/home', name: 'home', components: {
        default: () => import('@/views/home/HomeView.vue'),
        footer: () => import('@/views/FooterCom.vue')
      }
    },
    {
      path: '/kind', name: 'kind', components: {
        default: () => import('@/views/kind/KindView.vue'),
        footer: () => import('@/views/FooterCom.vue')
      }
    },
    {
      path: '/cart', name: 'cart', meta: { requiresAuth: true }, components: {
        default: () => import('@/views/cart/CartView.vue'),
        footer: () => import('@/views/FooterCom.vue')
      }
    },
    {
      path: '/my', name: 'my', meta: { requiresAuth: true }, components: {
        default: () => import('@/views/wode/MyView.vue'),
        footer: () => import('@/views/FooterCom.vue')
      }
    },
    {
      path: '/detail/:id', name: 'detali', meta: { requiresAuth: true }, components: {
        default: () => import('@/views/detail/DetaliView.vue')
      }
    },
    {
      path: '/register', name: 'register', components: {
        default: () => import('@/views/register/RegisterView.vue')
      }, children: [
        { path: "/register/", redirect: "/register/checktel" },
        { path: 'checktel', component: () => import('@/views/register/components/CheckTel.vue') },
        { path: 'sendmsg', component: () => import('@/views/register/components/SendMsg.vue') },
        { path: 'sendpass', component: () => import('@/views/register/components/SendPass.vue') }
      ]
    },
    {
      path: '/login', name: 'login', components: {
        default: () => import('@/views/register/Login.vue')
      }
    }
  ],
})


router.beforeEach((to, from) => {
  // 而不是去检查每条路由记录
  // to.matched.some(record => record.meta.requiresAuth)
  if (to.meta.requiresAuth && !auth.isLoggedIn()) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再来
      query: { redirect: to.fullPath },
    }
  }
})
export default router
